/****************************************************
	文件：ResLoader.cs
	作者：HuskyT
	邮箱：1005240602@qq.com
	日期：2020/9/7 10:31:47
	功能：资源加载器
*****************************************************/

using System;
using UnityEngine;
using HTUtility;

namespace HTFramework.ResKit
{
    public class ResLoader : Singleton<ResLoader>
    {
        public void Init()
        {
            HTLogger.Info("ResLoader init done.");
        }

        /// <summary>
        /// 同步资源加载
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="path"></param>
        /// <returns></returns>
        public T LoadSync<T>(string path) where T : UnityEngine.Object
        {
            ResItem resItem = ResRecorder.Instance.GetResItem(path);
            resItem.DoLoadSync();
            return resItem.Obj as T;
        }

        /// <summary>
        /// 异步资源加载
        /// </summary>
        /// <param name="path"></param>
        /// <param name="onLoaded"></param>
        public void LoadAsync(string path, Action<ResItem> onLoaded)
        {
            ResItem resItem = ResRecorder.Instance.GetResItem(path);
            resItem.SubscribeLoadedEvent(onLoaded);
            resItem.DoLoadAsync();
        }

        /// <summary>
        /// 预加载（同步）
        /// </summary>
        /// <param name="path"></param>
        public void PreLoad(string path)
        {
            ResItem resItem = ResRecorder.Instance.GetResItem(path);
            resItem.DoLoadSync();
            Release(resItem, false);
        }
        /// <summary>
        /// 预加载（异步）
        /// </summary>
        /// <param name="path"></param>
        /// <param name="onLoaded"></param>
        public void PreLoad(string path, Action<ResItem> onLoaded)
        {
            ResItem resItem = ResRecorder.Instance.GetResItem(path);
            resItem.SubscribeLoadedEvent((item) =>
            {
                onLoaded(item);
                Release(resItem, false); //完成回调中执行卸载
            });
            resItem.DoLoadAsync();
        }

        /// <summary>
        /// 通过资源路径卸载资源
        /// </summary>
        /// <param name="path"></param>
        public void Release(string path, bool clearMemory = true)
        {
            Release(ResRecorder.Instance.GetResItem(path), clearMemory);
        }
        /// <summary>
        /// 通过ResItem引用卸载资源
        /// </summary>
        /// <param name="resItem"></param>
        public void Release(ResItem resItem, bool clearMemory = true)
        {
            resItem.DoRelease(clearMemory);
        }
    }
}
